const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
// 装车
router.post('/deliver/toCargo', async ctx => {
    let tenantId = ctx.user.tenantId;
    let body = ctx.request.body;
    let uid = ctx.user.id;
    let name = ctx.user.name;
    let id = ctx.request.body.id;
    let ctime = tool.getTime();
    let deliverIds = ctx.request.body.deliverIds;
    if (tool.xe.isString(deliverIds)) {
        deliverIds = JSON.stringify(deliverIds)
    }
    if (deliverIds.length === 0) {
        return ctx.err('请选择送货员');
    }
    let cargo = {
        tenantId:tenantId,
        carsId: body.carsId,
        licence: body.licence,
        driverId: body.driverId,
        driverName: body.driverName,
        deliverIds: JSON.stringify(body.deliverIds),
        deliverNames: body.deliverNames,
        areaId: body.areaId?body.areaId:0
    }
    let billDate = tool.getDay()
    let billDateNo = tool.getDay('',0,'','YYYYMMDD')
    if (!id) {
        cargo.billDate = billDate;
        cargo.cby = uid;
        cargo.cbyName = name;
        cargo.ctime = ctime;
        cargo.state = 1;
        let cgo = await db.models['cargo'].findOne({
            where: {
                tenantId,
                billDate: cargo.billDate
            },
            order: [['id', 'desc']]
        })
        if (cgo) {
            let bno = cgo.billNo.split('-')
            let c = tool.xe.toInteger(bno[1]) + 1;
            cargo.billNo = 'PS' + billDateNo + '-' + c;
        } else {
            cargo.billNo = 'PS' +billDateNo + '-1';
        }
    }
    if (id) {
        cargo.uby = uid;
        cargo.utime = ctime;
    }

    let cargoId = await db.transaction(async () => {
        let cargoModel = await db.models['cargo'].create(cargo, )
        let strinsert = []
        for (let i = 0; i < body.bills.length; i++) {
            strinsert.push({
                tenantId,
                cargoId: cargoModel.id,
                iid: body.bills[i],
                state: 1
            })
        }
        await db.models['cargoInvoice'].bulkCreate(strinsert, )
        cargo.id = cargoModel.id;
        // 更新送货员为票据的送货员
        let sql = `update a set a.deliverIds=b.deliverIds,a.deliverNames=b.deliverNames from invoice a inner join (
            SELECT DISTINCT b.iid billId,SUBSTRING(deliverIds, 2, len(deliverIds)-2) deliverIds,deliverNames from cargo a inner join cargo_invoice b on a.id=b.cargoId and a.id=${cargoModel.id}
        ) b on a.id=b.billId`
        await db.query(sql, {type: QueryTypes.UPDATE}, )
        return cargoModel.id;
    })
    cargo.cargo = await tool.unDeliver(cargoId);
    // 更新主票据的searchTxt 为主表billNo+licence+deliverNames+销售单位billNo
    let updateTxt = `update a set a.searchTxt = b.txt from cargo a inner join(
    SELECT a.id, concat(a.billNo, ',', a.licence, ',', a.deliverNames, ',', b.billNo) txt from cargo a inner join(
        SELECT cargoId, billNo = stuff((
        select ',' + [billNo] from(SELECT a.cargoId, b.billNo from cargo_invoice a inner join invoice b on a.iid = b.id and a.cargoId =${
        cargoId
    }) t where t.cargoId = cargo_invoice.cargoId
    for xml path('')), 1, 1, '') from cargo_invoice where cargoId =${cargoId} GROUP BY cargoId) b on a.id = b.cargoId) b on a.id = b.id `
    db.query(updateTxt, {type: QueryTypes.UPDATE})
    return ctx.suc('已装车', cargo);
})




module.exports = router;
